//
//  HWGameCommunityListController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/10/18.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import JXPagingView
import ZLPhotoBrowser
class HWGameCommunityListController: HWBaseViewController {
    /// 社区id
    @objc var communityId = ""
    /// 分类
    var type = ""
    var collectionView:UICollectionView!
    var collectionProtocol = HWGameCommunityListProtocol()
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    var httpManager = HWGameCommunityHttpManager()
    var modelArr:[HWGameCommunityListModel] = []
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        
        let flowL = UICollectionViewFlowLayout.init()
        flowL.minimumLineSpacing = 0
        flowL.minimumInteritemSpacing = 0
        flowL.scrollDirection = .vertical
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowL)
        collectionView.delegate = collectionProtocol
        collectionView.dataSource = collectionProtocol
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.register(HWGameCommunityListCell.self, forCellWithReuseIdentifier: "HWGameCommunityListCell")
        collectionView.register(HWGameCommunityListHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HWGameCommunityListHeader")
        collectionView.register(HWGameCommunityListFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "HWGameCommunityListFooter")
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        loadData()
        
        addAction()
        
        addRefresh()
        
    }

}
extension HWGameCommunityListController:JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }
    
    func listScrollView() -> UIScrollView {
        return self.collectionView
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }
    
}

extension HWGameCommunityListController {
    private func initUI() -> Void {
        
        navigationView.isHidden = true
        self.view.backgroundColor = "#E8E9EB".toColor
        view.addSubview(collectionView)
        collectionView.ly_emptyView = LYEmptyView.emptyActionView(withImageStr: "", titleStr: "", detailStr: "暂无数据", btnTitleStr: "点击刷新", btnClick: {
            self.loadData()
        })
        collectionView.ly_emptyView.actionBtnCornerRadius = 15*widthScale
        collectionView.ly_emptyView.actionBtnHeight = 30*widthScale
        collectionView.ly_emptyView.contentViewOffset = -120*widthScale
    }
    
    private func initFrame() -> Void {
        collectionView?.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension HWGameCommunityListController {
    func addAction() -> Void {
        collectionProtocol.scrollDidScroll = {
            scrollView in
            self.listViewDidScrollCallback?(scrollView)
        }
        
        collectionProtocol.didSelectImage = {
            index,images in
            var datas: [Any] = []
            for a in images {
                if a.count > 0 {
                    datas.append(URL(string: a)!)
                }
            }
            let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
                
                return .image
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
            
        }
        
        collectionProtocol.didSelectVideo = {
            url in
            
            let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
                
                return .video
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
        }
        
        collectionProtocol.jumpToDetail = {
            mod in
            let detail = HWGameCommunityDetailController()
            detail.newsId = mod.id
            self.navigationController?.pushViewController(detail, animated: true)
        }
        
//        collectionProtocol.zanButtonClick = {
//            mod in
//            self.httpManager.gameCommunityZan(pid: mod.id, puid: mod.uid, type: "0") { message in
//                self.loadData()
//            } failure: { errorString in
//                self.view.showHUD(title: errorString)
//            }
//
//        }
        
        collectionProtocol.delButtonClick = {
            mod in
            let alert = UIAlertController(title: "删除文章", message: "是否确认删除？", preferredStyle: UIAlertController.Style.alert)
            alert.addAction(UIAlertAction(title: "确认", style: .default, handler: { action in
                self.httpManager.gameCommunityCommentDel(id: mod.id) { nessage in
                    self.loadData()
                } failure: { errorString in
                    self.view.showHUD(title: errorString)
                }
            }))
            alert.addAction(UIAlertAction(title: "取消", style: .default, handler: { action in
                
            }))
            self.present(alert, animated: true)

        }
    }
}

extension HWGameCommunityListController {
    
    func loadData() -> Void {
        self.collectionView.mj_footer?.endRefreshing()
        httpManager.getGameCommunityList(communityId: communityId, type: type) { models in
            self.modelArr = models
            self.collectionProtocol.models = models
            self.collectionView.reloadData()
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.isHidden = false
        } failure: { errorString in
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            self.view.showHUD(title: errorString)
        }

    }
    
    func addRefresh() -> () {
        
        collectionView.mj_header = MJRefreshNormalHeader()
        collectionView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        collectionView.mj_footer = MJRefreshBackNormalFooter()
        collectionView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        collectionView.mj_footer?.isHidden = true
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.collectionView.mj_footer?.endRefreshing()
        httpManager.getGameCommunityListFooter(communityId: communityId, type: type) { models in
            self.collectionView.mj_footer?.endRefreshing()
            if models.count > 0 {
                for mod in models {
                    self.modelArr.append(mod)
                }
            }
            self.collectionProtocol.models = self.modelArr
            self.collectionView.reloadData()
        } failure: { error in
            self.collectionView.mj_footer?.endRefreshing()
        }
    }
}


